package com.demo.las.controller;

import com.demo.las.dto.ApiResponse;
import com.demo.las.entity.User;
import com.demo.las.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public ApiResponse<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return ApiResponse.success(users);
    }

    @GetMapping("/{id}")
    public ApiResponse<User> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id).orElse(null);
        if (user == null) {
            return ApiResponse.error(404, "用户不存在");
        }
        return ApiResponse.success(user);
    }

    @PostMapping
    public ApiResponse<User> createUser(@Valid @RequestBody User user) {
        try {
            User createdUser = userService.createUser(user);
            return ApiResponse.success("用户创建成功", createdUser);
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public ApiResponse<User> updateUser(@PathVariable Long id, @Valid @RequestBody User user) {
        User existingUser = userService.getUserById(id).orElse(null);
        if (existingUser == null) {
            return ApiResponse.error(404, "用户不存在");
        }
        
        user.setId(id);
        User updatedUser = userService.updateUser(user);
        return ApiResponse.success("用户更新成功", updatedUser);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteUser(@PathVariable Long id) {
        User user = userService.getUserById(id).orElse(null);
        if (user == null) {
            return ApiResponse.error(404, "用户不存在");
        }
        
        userService.deleteUser(id);
        return ApiResponse.success("用户删除成功", null);
    }
}


